<template>
  <div id="chat">
    <!-- 顶部导航栏 -->
    <div style="position: fixed;top: 0;width: 100%;z-index:2000">
      <van-nav-bar class="navbar" @click-left="onClickLeft" @click-right="onClickRight">
        <template #left>
          <van-icon name="arrow-left" class="left" />
        </template>
        <template #title>
          <div class="title">{{item.users.name||$route.query.name}}</div>
        </template>
        <template #right>
          <van-icon name="user-o" class="right" />
        </template>
      </van-nav-bar>
      <!-- 聊天的内容 -->
      <van-pull-refresh v-model="isLoading" @refresh="onRefresh">     
      <div class="chatContent" id="chat">
        <div v-for="(items, index) in messageList" :key="index">
          <!-- 对方发消息 -->
          <div v-if="item.users.name ==items.from" class="otherTalk">
            <van-image
              round
              fit="cover"
              :src="item.users.img"
              class="img"
            />
            <span class="content">
            
              {{items.payload.text}}
            </span>
          </div>
          <!-- 自己发消息 -->
          <div v-else class="youTalk">
            <span class="content">
              {{items.payload.text}}
            </span>
            <van-image
              round
              fit="cover"
              :src="receiveName"
              class="img"
            />
          </div>
        </div>
      </div>
        </van-pull-refresh>
      <!-- 输入框 -->
      <div class="send">
        <van-field style="background: #9ad5a7">
          <template #button>
            <van-button class="btn" type="info" round @click="send" :disabled="text.trim() == ''">发送</van-button>
          </template>
          <template #input>
            <input class="input" type="text" v-model="text">
          </template>
        </van-field>
      </div>
    </div>
  </div>
</template>

<script>
import { Toast } from 'vant';
export default {
  name: 'Chat',
  data () {
    return {
      users: [
        // id: 1是对方 2是自己
      ],
      text: '', // 用户输入框的内容
      word: '', // 储存用户输入框的内容
      messageList:[],
      nextReqMessageID:[],
      receiveText:'',
      isCompleted:true,
      item:{
        users:{
          name:''
        }
      },
      simple:false,
      receiveName:'',
      isLoading: false,
       count: 0,
    }
  },
  methods: {
    onClickLeft() {
        this.$router.push('/home')
        this.logout();
    },
    onClickRight() {
      console.log("点击了用户的信息")
      this.$router.push({path:'/user',query:{name:this.item.users.name}})
         this.logout();
    },
     login(){
            let promise = this.tim.login({userID: localStorage.userid, userSig: localStorage.usersig});
            console.log(promise);
            promise.then(function(imResponse) {
            console.log(imResponse.data); // 登录成功
            }).catch(function(imError) {
            console.warn('login error:', imError); // 登录失败的相关信息
            });
        },
        logout(){
            let promise = this.tim.logout();
            promise.then(function(imResponse) {
            console.log(imResponse.data); // 登出成功
            }).catch(function(imError) {
            console.warn('logout error:', imError);
            });
        },
        send(){
            this.word = this.text
            this.text=""
            let message = this.tim.createTextMessage({
            to: this.item.users.name,
            conversationType: this.TIM.TYPES.CONV_C2C,
            payload: {
                text: this.word
            }
            });
            // 2. 发送消息
            this.messageList.push(message);
            console.log(message);
            let promise = this.tim.sendMessage(message);
            promise.then((imResponse)=> {
            // 发送成功
              let t = document.getElementsByClassName('chatContent')[0];
              t.scroll({ top: t.scrollHeight, left: 0, behavior: 'smooth' });
              // this.onSdkReady();
              console.log(imResponse)
              console.log(document.body.clientHeight);
            }).catch((imError)=> {
            // 发送失败
            console.warn('sendMessage error:', imError);
            });
        },
        receive(){
            var _this = this;
            let onMessageReceived = function(event) {
            // event.data - 存储 Message 对象的数组 - [Message]
            _this.receiveText = event.data[0].payload.text;
            _this.messageList.push(event.data[0]);
            console.log(event);
            };
            this.tim.on(this.TIM.EVENT.MESSAGE_RECEIVED, onMessageReceived)
        },
         onRefresh() {
      setTimeout(() => {
        Toast('刷新成功');
        this.onSdkReadys();
        this.isLoading = false;
        this.count++;
      }, 1000);

    },
         onSdkReady() {
            var _this =this;
               let promise = this.tim.getMessageList({conversationID: 'C2C'+this.item.users.name,count: 15});
                promise.then((imResponse)=> {
                const messageList = imResponse.data.messageList; // 消息列表。
                const nextReqMessageID = imResponse.data.nextReqMessageID; // 用于续拉，分页续拉时需传入该字段。
                const isCompleted = imResponse.data.isCompleted; // 表示是否已经拉完所有消息。
                _this.messageList = messageList;
                _this.nextReqMessageID = nextReqMessageID;
                _this.isCompleted = isCompleted;
                console.log(messageList);
                }).catch((imError)=>{
                  console.log(imError);
                });
        },
         onSdkReadys(){
                var _this =this;
                if(_this.nextReqMessageID&&!_this.isCompleted){
                 let promise = this.tim.getMessageList({conversationID: 'C2C'+this.item.users.name,count: 15,nextReqMessageID:_this.nextReqMessageID});
                 promise.then((imResponse)=> {
                const messageList = imResponse.data.messageList; // 消息列表。
                const nextReqMessageID = imResponse.data.nextReqMessageID; // 用于续拉，分页续拉时需传入该字段。
                const isCompleted = imResponse.data.isCompleted; // 表示是否已经拉完所有消息。
                for(var message of messageList){
                  _this.messageList.unshift(message);
                }
                _this.nextReqMessageID = nextReqMessageID;
                _this.isCompleted = isCompleted;
                console.log(messageList);
                 }).catch((imError)=>{
                   console.log(imError);
                });
             }
            
            },
        find(){
           let params = new URLSearchParams();
          params.append('name',this.$route.query.name)
          this.axios({
          method: "get",
          url: this.$store.state.url+"/order/user/orderuser",
          headers:{
           'Authorization': localStorage.token
                },
          params
        }).then((res) => {
            this.item.users.img ="http://picture.105577.xyz/" +res.data.data.img;
            this.item.users.name =res.data.data.name;
            console.log(this.item)
        }).catch((err) => {
            console.log(err);
        })
        },
        getImg(){
          this.axios({
          method: "get",
          url: this.$store.state.url+"/order/"+this.$route.query.id,
      }).then((res) => {
          res.data.data.img  = JSON.parse( res.data.data.img);
          res.data.data.imgCount = Object.keys(res.data.data.img);
          for(var t in res.data.data.imgCount){
            res.data.data.img[t] = "http://picture.105577.xyz/"+res.data.data.img[t];
          }
          res.data.data.users.img = "http://picture.105577.xyz/"+  res.data.data.users.img;
          if( res.data.data.receiving_user){
           res.data.data.receiving_user.img = "http://picture.105577.xyz/"+  res.data.data.receiving_user.img;
          }
          this.item = res.data.data;
        console.log(this.item);
      }).catch((err) => {
          console.log(err);
      })
        }
   
  },
  created(){
    this.receiveName=JSON.parse(window.localStorage.getItem('user')).img;
    console.log(this.$route.query.name);
    if(this.$route.query.id){
       this.getImg();
    } 
    if(this.$route.query.name){
         this.find();   
    }
    // this.inform();
    this.login();
    this.tim.on(this.TIM.EVENT.SDK_READY, this.onSdkReady);
      // this.receiveAll();  
  },
  mounted() {
    this.receive();
    console.log(document.getElementById('chat').scrollHeight)
    // this.tim.on(this.TIM.EVENT.SDK_READY, this.send);
    this.tim.setMessageRead({conversationID: 'C2Cexample'});
  },
}
</script>

<style scoped>
  .navbar {
    background: #66cd99;
    box-shadow: 0 0px 5px #9ad5a7;
    color: #9ad5a7;
  }
  .title {
    color: #fff;
    font-size: 20px
  }
  .left {
    color: #fff;
    font-size: 20px
  }
  .right {
    color: #fff;
    font-size: 20px
  }
  .chatContent {
    width: 100%;
    height: calc(100vh - 46px - 64px);
    overflow: auto
  }
  .otherTalk {
    display: flex;
    align-items: center;
    justify-content: left;
    margin: 20px 0
  }
  .youTalk {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    margin: 20px 0
  }
  .img {
    margin: 5px;
    border: 1px solid #cccccc;
    width: 45px;
    height: 45px
  }
  .content {
    max-width: 250px;
    padding: 10px;
    border-radius: 10px;
    background: #fff;
    word-break:break-all;
    font-size: 18px;
  }
  .send {
    position: fixed;
    bottom: 0;
    width: 100%;
    border: 0;
  }
  .input {
    outline: none;
    border: 0;
    border-radius: 20px;
    width: 250px;
    height: 40px;
    padding-left: 20px;
    padding-top: 3px;
   font-size: 20px;
  }
  .btn{
    width: 70px;
  }
</style>